package com.daikit.daikit4gxt.client.utils.miscs;

import com.daikit.commons.shared.exception.DkUnknownErrorException;
import com.daikit.daikit4gxt.client.DkBaseConfiguration;
import com.daikit.daikit4gxt.client.DkBaseMain;
import com.daikit.daikit4gxt.client.constants.DkErrorCodes;
import com.daikit.daikit4gxt.client.log.DkLogger;
import com.google.gwt.user.client.Timer;


/**
 * Utility class for time associated methods
 *
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 */
public class DkTimerUtils
{

	/**
	 * Wrapper to {@link #executeDelayed(DkDelayedExecution, int)} with <br>
	 * delay = DkBaseMain.config().getTimerDefaultDelayMilliseconds() =
	 * {@link DkBaseConfiguration#getTimerDefaultDelayMilliseconds()}
	 *
	 * @param delayedExecution
	 */
	public static void executeDelayed(final DkDelayedExecution delayedExecution)
	{
		executeDelayed(delayedExecution, DkBaseMain.config().getTimerDefaultDelayMilliseconds());
	}

	/**
	 * Execute the given {@link DkDelayedExecution} with given delay
	 *
	 * @param delayedExecution
	 *           the {@link DkDelayedExecution} to be executed after delay
	 * @param delayMilliseconds
	 *           the delay in milliseconds to wait before running given {@link DkDelayedExecution}
	 */
	public static void executeDelayed(final DkDelayedExecution delayedExecution, final int delayMilliseconds)
	{
		final Timer timer = new Timer()
		{
			@Override
			public void run()
			{
				try
				{
					delayedExecution.run();
				}
				catch (final Throwable t)
				{
					if (DkBaseMain.controller().isChainActionRunning())
					{
						throw new DkUnknownErrorException(DkErrorCodes.DK4GXT00003, t.getMessage(), t);
					}
					else
					{
						DkLogger.error(DkTimerUtils.class, "Error while delaying execution: " + t.getMessage(), t);
					}
				}
			}
		};
		timer.schedule(delayMilliseconds);
	}

}
